import os
from PIL import Image

def compress_images(input_folder, quality):
    # 确定输出文件夹路径为输入路径同级的 "out"
    output_folder = os.path.join(input_folder, "out")

    # 确保输出文件夹存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍历输入文件夹中的所有文件
    for root, dirs, files in os.walk(input_folder):
        for file in files:
            if file.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp")):
                input_path = os.path.join(root, file)
                output_path = os.path.join(output_folder, file)

                try:
                    with Image.open(input_path) as img:
                        img = img.convert("RGB")  # 确保所有图像是RGB格式
                        img.save(output_path, "JPEG", quality=quality)
                        print(f"Compressed: {input_path} → {output_path}")
                except Exception as e:
                    print(f"Failed to compress {input_path}: {e}")

if __name__ == "__main__":
    input_folder = "D:\\WorkSpace_code\\sidland\\files\\blogs\\life\\informal\\dongbeilaojia"

    if not os.path.exists(input_folder):
        print("The specified input folder does not exist. Please check the path.")
    else:
        quality = 30  # 默认图片压缩质量
        compress_images(input_folder, quality)